<template>
  <div id="app">
    <h2 style="position: fixed; z-index: 999; background: white; width: 100%; margin: 0; padding: 10px;">
      高德地图示例
    </h2>


    <div class="control-panel">
      <button @click="openWebSocket" :disabled="ws && ws.readyState === 1">打开连接</button>
      <button @click="closeWebSocket" :disabled="!ws || ws.readyState === 3">关闭连接</button>
    </div>

    <div id="mapContainer"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      marker: null,
      currentPos: null,
      targetPos: null,
      animating: false,
      ws: null,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // 初始化高德地图
    initMap() {
      this.map = new AMap.Map("mapContainer", {
        center: [87.616847, 43.825592],
        zoom: 13,
      });

      this.currentPos = { lng: 87.616847, lat: 43.825592 };
      this.targetPos = { lng: 87.616847, lat: 43.825592 };
      this.updateMarker(this.currentPos.lng, this.currentPos.lat);
    },

    // 打开 WebSocket
    openWebSocket() {
      // 若已有连接先关闭旧的
      if (this.ws && this.ws.readyState === 1) {
        console.log("WebSocket 已连接");
        return;
      } else if (this.ws) {
        this.closeWebSocket();
      }

      const wsUrl = "ws://localhost:8080/websocket/carInfo";
      this.ws = new WebSocket(wsUrl);

      this.ws.onopen = () => {
        console.log("✅ WebSocket 已连接");
      };

      this.ws.onmessage = (event) => {
        if (!this.ws) return; // 防止关闭后继续触发
        try {
          const data = JSON.parse(event.data);
          console.log("收到消息：", data);

          if (data.x && data.y) {
            this.targetPos = { lng: data.x, lat: data.y };
            if (!this.animating) {
              this.animateMarker();
            }
          }
        } catch (e) {
          console.warn("收到非坐标格式消息：", event.data);
        }
      };

      this.ws.onerror = (err) => {
        console.error("WebSocket 连接异常：", err);
      };

      this.ws.onclose = () => {
        console.warn("WebSocket 已断开");
        this.ws = null;
      };
    },

    // 关闭 WebSocket
    closeWebSocket() {
      if (this.ws) {
        console.log("🛑 正在关闭 WebSocket...");
        // 清除所有事件监听器
        this.ws.onmessage = null;
        this.ws.onerror = null;
        this.ws.onclose = null;
        this.ws.onopen = null;
        this.ws.close();
        this.ws = null;
      }
    },

    // 设置或更新车辆标记点
    updateMarker(lng, lat) {
      if (!this.marker) {
        this.marker = new AMap.Marker({
          position: [lng, lat],
          title: "车辆位置",
        });
        this.marker.setMap(this.map);
      } else {
        this.marker.setPosition([lng, lat]);
      }
      this.map.setCenter([lng, lat]);
    },

    // 平滑移动图标
    animateMarker() {
      this.animating = true;
      const stepCount = 60;
      let step = 0;

      const startLng = this.currentPos.lng;
      const startLat = this.currentPos.lat;
      const endLng = this.targetPos.lng;
      const endLat = this.targetPos.lat;

      const animate = () => {
        step++;
        const progress = step / stepCount;
        const lng = startLng + (endLng - startLng) * progress;
        const lat = startLat + (endLat - startLat) * progress;
        this.updateMarker(lng, lat);

        if (step < stepCount) {
          requestAnimationFrame(animate);
        } else {
          this.currentPos = { lng: endLng, lat: endLat };
          this.animating = false;

          // 位置未同步时，继续动
          if (this.currentPos.lng !== this.targetPos.lng || this.currentPos.lat !== this.targetPos.lat) {
            this.animateMarker();
          }
        }
      };

      animate();
    },
  },

  // 组件销毁前清理连接
  beforeDestroy() {
    this.closeWebSocket();
  }
};
</script>

<style scoped>
html, body, #app, #mapContainer {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

#mapContainer {
  position: absolute;
  top: 40px;
  bottom: 0;
  left: 0;
  right: 0;
  border: none;
}

.control-panel {
  position: fixed;
  right: 10px;
  top: 60px;
  z-index: 1000;
  background: white;
  border: 1px solid #ccc;
  padding: 8px;
  border-radius: 4px;
}

.control-panel button {
  margin-bottom: 5px;
  width: 100px;
}
</style>
